package com.carey.myblog.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carey.myblog.pojo.Message;
import com.carey.myblog.pojo.User;
import com.carey.myblog.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class MessageController {
    @Autowired
    private MessageService messageService;

    @Value("${avatar}")
    private String avatar;

    @GetMapping("/messageBoard")
    public String messageBoard(){

        return "message_board";
    }

    @GetMapping("/Messages")
    public String getmessages(@RequestParam(value = "page",defaultValue = "1")Integer page,
                             @RequestParam(value = "rows",defaultValue = "8")Integer rows,
                             HttpSession session,
                             Model model){
        /*Integer current = (Integer) session.getAttribute("current");
        if (current==null){
            current=page;
        }*/
        Integer current = page;
        Integer limmit = rows;
        Page<Message> messagePage = messageService.getMessage(current,limmit);
        List<Message> records = messagePage.getRecords();
        model.addAttribute("page",messagePage);
        //session.setAttribute("current",page);//将当前页数存在session中
        return "message_board";
    }

    @PostMapping("/POSTMessages")
    public String post(Message message, HttpSession session){
        //TODO
        User user = (User) session.getAttribute("user");
        if (user!=null){
            message.setAdminmessage(2);
            message.setAvatar(user.getAvatar());
        }else {
            message.setAdminmessage(0);
            message.setAvatar(avatar);
        }
        messageService.saveMessage(message);
        messageService.sendemail(message);

        //Integer current = (Integer) session.getAttribute("current");//目的是为了回复后可以刷新到当前页
        //return "redirect:/Message?page="+current;
        return "redirect:/Message";
    }

    @GetMapping("/Message")
    public String getmessage(@RequestParam(value = "page",defaultValue = "1")Integer page,
                             Model model){
        Integer current = page;
        Integer limmit = 8;
        Page<Message> messagePage = messageService.getMessage(current,limmit);
        model.addAttribute("page",messagePage);
        return "message_board :: messageList";
    }
}
